/**
 * 表单组件编译逻辑 v1.0
 */

import { computed, defineComponent, h, resolveComponent } from "vue"
export default defineComponent({
  props: {
    item: {
      type: Object,
      default: () => null
    },
    modelValue: {
      type: [String, Number, Array, Boolean],
      default: () => null
    }
  },
  emits: ['update:modelValue'],
  setup(props, { emit }) {

    // binding props
    const bindProps = computed(() => {
      const opts: any = {}
      const data = props.item
      for (const key in data) {
        if (data[key]) opts[key] = data[key]
      }
      delete opts.__config__
      delete opts.__slot__
      delete opts.__methods__

      switch (props.item.__config__.layout) {
        case "colFormItem":
          if (props.item.__vModel__) {
            opts.value = props.modelValue
            opts.onChange = (e) => {
              let newVal: any = null
              if (Array.isArray(e) || typeof e !== 'object') newVal = e
              else newVal = e?.target?.value
              emit('update:modelValue', newVal)
            }
          }
          break;
        default:
          break;
      }
      return opts
    })
    return () => h(resolveComponent('a-col'), {
      span: props.item.__config__.span || '',
      class: 'form-item-a-col',
    }, () => [
      h(resolveComponent('a-form-item'), {
        label: (props.item.__config__.showLabel ? props.item.__config__.label : '') || '',
        name: props.item.__vModel__,
        required: props.item.__config__.required
      }, () => [h(resolveComponent(props.item.__config__.tag), bindProps.value)])
    ])
  }
})